package com.quanshu.exchange.ui.gui.message.chat.input;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMError;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.chat.ChatCommonUtils;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseDialog;
import com.quanshu.exchange.ui.gui.message.chat.row.ChatRowVoicePlayer;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2018/1/17.
 */

public class DialogChatRecorder extends BaseDialog {

    @BindView(R.id.chat_voice_start_recorder_btn)
    ImageView recorderBtn;
    @BindView(R.id.chat_recorder_state)
    TextView chatRecorderState;
    @BindView(R.id.chat_recorder_delete_btn)
    ImageView chatRecorderDeleteBtn;

    private View view;
    private Context context;

    protected Drawable[] micImages;
    protected VoiceRecorder voiceRecorder;
    protected PowerManager.WakeLock wakeLock;
    ChatRowVoicePlayer voicePlayer;

    protected Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // change image
            if (msg.what > 14) {
                msg.what = 14;
            }
            recorderBtn.setImageDrawable(micImages[msg.what]);
        }
    };

    public DialogChatRecorder(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(context).inflate(R.layout.dialog_voice_recorder, null);
        setContentView(view);
        ButterKnife.bind(this);
        prepareRecord();
    }

    public void onTouch(MotionEvent event, VoiceRecorderCallback recorderCallback) {
        int action = event.getAction();
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        // 按下
        if (action == event.ACTION_DOWN) {
            try {
                voicePlayer = ChatRowVoicePlayer.getInstance(context);
                if (voicePlayer.isPlaying())
                    voicePlayer.stop();
                startRecording();
            } catch (Exception e) {
                setStateText(3, 0);
            }
        }
        // 移动
        else if (action == event.ACTION_MOVE) {
            // 如果在删除按钮内
            if (isTouchPointInView(chatRecorderDeleteBtn, x, y)) {
                setStateText(2, 0);
            } else {
                setStateText(1, 2);
            }
        }
        // 抬起
        else if (action == event.ACTION_UP) {
            // 如果在删除按钮内
            if (isTouchPointInView(chatRecorderDeleteBtn, x, y)) {
                dismiss();
            } else {
                try {
                    int length = stopRecoding();
                    if (length > 0) {
                        if (recorderCallback != null) {
                            recorderCallback.onVoiceRecordComplete(getVoiceFilePath(), length);
                        }
                    } else if (length == EMError.FILE_INVALID) {
                        Toast.makeText(context, R.string.Recording_without_permission, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, R.string.The_recording_time_is_too_short, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, R.string.send_failure_please, Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            dismiss();
        }
    }

    private void prepareRecord() {
        setStateText(0, 0);
        voiceRecorder = new VoiceRecorder(micImageHandler);
        // animation resources, used for recording
        micImages = new Drawable[]{
                context.getResources().getDrawable(R.drawable.icon_recording_f1),
                context.getResources().getDrawable(R.drawable.icon_recording_f1),
                context.getResources().getDrawable(R.drawable.icon_recording_f1),
                context.getResources().getDrawable(R.drawable.icon_recording_f2),
                context.getResources().getDrawable(R.drawable.icon_recording_f2),
                context.getResources().getDrawable(R.drawable.icon_recording_f2),
                context.getResources().getDrawable(R.drawable.icon_recording_f3),
                context.getResources().getDrawable(R.drawable.icon_recording_f3),
                context.getResources().getDrawable(R.drawable.icon_recording_f3),
                context.getResources().getDrawable(R.drawable.icon_recording_f4),
                context.getResources().getDrawable(R.drawable.icon_recording_f4),
                context.getResources().getDrawable(R.drawable.icon_recording_f4),
                context.getResources().getDrawable(R.drawable.icon_recording_f5),
                context.getResources().getDrawable(R.drawable.icon_recording_f5),
                context.getResources().getDrawable(R.drawable.icon_recording_f5)};
        wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "record");
    }

    // 开始录制
    public void startRecording() {
        if (!ChatCommonUtils.isSdcardExist()) {
            ToastHelper.toast(context.getResources().getString(R.string.Send_voice_need_sdcard_support));
            return;
        }
        try {
            wakeLock.acquire();
            voiceRecorder.startRecording(context);
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld())
                wakeLock.release();
            if (voiceRecorder != null)
                voiceRecorder.discardRecording();
            ToastHelper.toast(context.getResources().getString(R.string.recoding_fail));
            return;
        }
    }

    //  丢弃错误录制
    public void discardRecording() {
        if (wakeLock.isHeld())
            wakeLock.release();
        try {
            // stop recording
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
            }
        } catch (Exception e) {
        }
    }

    // 停止录制
    public int stopRecoding() {
        if (wakeLock.isHeld())
            wakeLock.release();
        return voiceRecorder.stopRecoding();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }

    // 0:准备中 ， 1：正在录制 ， 2：松手取消发送 , 3:录制失败
    private void setStateText(int state, int time) {
        if (state == 0) {
            chatRecorderState.setText("准备中");
        } else if (state == 1) {
            chatRecorderState.setText("正在录制");
        } else if (state == 2) {
            chatRecorderState.setText("松手取消发送");
        } else if (state == 3) {
            chatRecorderState.setText("录制失败");
        }
    }

    //(x,y)是否在view的区域内
    private boolean isTouchPointInView(View view, int x, int y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getMeasuredWidth();
        int bottom = top + view.getMeasuredHeight();
        //view.isClickable() &&
        if (y >= top && y <= bottom && x >= left
                && x <= right) {
            return true;
        }
        return false;
    }


    @Override
    public boolean isCancelAble() {
        return false;
    }

    @Override
    public void init(@NonNull Context context) {
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        //默认的Dialog只有5/6左右的宽度，改为全屏宽度,由dialog的布局自己来决定实际显示宽度
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    public interface VoiceRecorderCallback {
        /**
         * on voice record complete
         *
         * @param voiceFilePath   录音完毕后的文件路径
         * @param voiceTimeLength 录音时长
         */
        void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength);
    }

    @Override
    public void dismiss() {
        discardRecording();
        super.dismiss();
    }
}